<template>
  <section>
      <div class="filter-container">
            <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
            <el-button size="mini" class="ml10" @click="handleExpand" type="primary">全部展开/收缩</el-button>
        </div>
        <el-table
                row-key="id"
                ref="ctab"
                :default-expand-all="isExpand"
                :data="tree_list"
                style="width: 100%">
            <el-table-column align="left" label="分销商品分类名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="分类id">
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="图片">
                <template slot-scope="scope">
                    <img v-if="scope.row.extra.picture" :src="scope.row.extra.picture | thumbnail" :data-origin="scope.row.picture" class="img-thumbnail" width="60" />
                </template>
            </el-table-column>
            <el-table-column align="center" label="排序">
                <template slot-scope="scope">
                    <span>{{scope.row.orderNum}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                    <el-tag :type="getStatusColor(scope.row.extra)">{{getStatusText(scope.row.extra)}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                <template slot-scope="scope">
                    <el-dropdown>
                        <el-button
                                type="text">
                            操作<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <!-- <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[20,30, 50]" :page-size="listQuery.num" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div> -->

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="500px" @close="dialogClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px">
                <el-form-item label="上级分类" prop="parentId">
                    <el-cascader
                        :disabled="form.id>0"
                        v-model="form.parentIdList"
                        size="mini"
                        :options="tree_list"
                        :props="props">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="分销商品分类名称" prop="name">
                    <common-input v-model="form.name" placeholder="请输入分销商品分类名称" maxlength="10" />
                </el-form-item>
                <el-form-item label="分销商品分类标识图" prop="picture">
                    <pic-sel style="float:left" v-model="form.picture" />
                </el-form-item>
                <el-form-item label="首页广告位" prop="adId">
                    <el-select size="mini" v-model="form.adId" placeholder="首页广告位" clearable>
                        <el-option
                                v-for="item in adList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="列表页广告位" prop="listAdId">
                    <el-select size="mini" v-model="form.listAdId" placeholder="列表页广告位" clearable>
                        <el-option
                                v-for="item in adList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="item in status_list" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="排序" prop="orderNum">
                    <common-input v-model="form.orderNum" class="w60" maxlength="3" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="cancel('form')">取消</el-button>
                <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
                <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
            </div>
        </el-dialog>
  </section>
</template>

<script>
    import {
        isIntegerNotMust
    } from '../../utils/validator'
    import {
        retail_product_cat_add,
        retail_product_cat_edit,
        retail_product_cat_del,
        retail_product_cat_detail,
        retail_product_cat_tree
    } from '../../api/retail_product';
    import {
        adAll
    } from '../../api/ad';
export default {
    components: {
        'pic-sel': () => import('../../components/PicSel/index')
    },
  data() {
    return {
        isExpand: false,
        adList: [],
        props: { value: 'id', label:'name', checkStrictly:true },
        list: null,
        listLoading: true,
        listQuery: {
            page: 1,
            num: 20,
            keyword: undefined,
            status: '',
            industryId: undefined,
        },
        status_list: [
            {
                value: 1,
                label: '可用'
            },
            {
                value: 2,
                label: '不可用'
            }
        ],
        total: null,
        dialogStatus: '',
        dialogFormVisible: false,
        textMap: {
            update: '编辑分销商品分类',
            create: '新增分销商品分类'
        },
        form: {
            id: undefined,
            name: undefined,
            picture: undefined,
            status: 1,
            orderNum: 0,
            parentId: 0,
            parentIdList:[],
            adId: undefined,
            listAdId: undefined,
        },
        rules: {
            name: [
                {
                    required: true,
                    message: '请输入分销商品分类名称',
                    trigger: 'blur'
                },
                {
                    max: 10,
                    message: '名称最多10个字',
                    trigger: 'blur'
                }
            ],
            orderNum: [
                {
                    validator: isIntegerNotMust,
                    trigger: 'blur'
                }
            ]
        },
        industry_list: [],
        tree_list: []
    }
  },
  mounted() {
  },
        created() {
            this.getAdList();
            this.getTree();
        },

  methods: {
    handleExpand() {
        this.isExpand = !this.isExpand
        this.$nextTick(() => {
            this.forArr(this.tree_list, this.isExpand)
        })
        // if(this.expandIds && this.expandIds.length > 0) {
        //     this.expandIds = [];
        // } else {
        //     this.tree_list.forEach((item)=>{
        //         this.expandIds.push(item.id)
        //     })
        // }
    },
    forArr(arr, isExpand) {
      arr.forEach(i => {
        // toggleRowExpansion见element文档
        this.$refs.ctab.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
      getAdList() {
          adAll().then((res)=>{
              this.adList = res.data;
          }).catch((err)=>{

          })
      },
    getTree() {
        retail_product_cat_tree(0).then((res)=>{
            this.tree_list = res.data;
        }).catch((err)=>{
        });
    },
    handleCreate() {
        this.resetTemp();
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
    },
    resetTemp() {
        this.form = {
            name: undefined,
            id: undefined,
            code: undefined,
            picture: undefined,
            status: 1,
            orderNum: 0,
            parentId: undefined,
            parentIdList: [],
            adId: undefined,
            listAdId: undefined,
        };
    },
    getStatusText(row) {
        if(row.status === 1) {
            return "可用"
        }

        return "不可用"
    },
    getStatusColor(row) {
        if(row.status === 1) {
            return "success"
        }

        return "danger"
    },
    create(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
            if (valid) {
                if(!this.form.orderNum) {
                    this.form.orderNum = 0;
                }
                if(!this.form.adId) {
                    this.form.adId = 0;
                }
                if(!this.form.listAdId) {
                    this.form.listAdId = 0;
                }
                let pid = 0;
                if(this.form.parentIdList && this.form.parentIdList.length > 0) {
                    pid = this.form.parentIdList[this.form.parentIdList.length - 1];
                }
                this.form.parentId = pid;
                retail_product_cat_add(this.form)
                    .then(() => {
                        this.dialogFormVisible = false;
                        // this.getList();
                        this.getTree();
                        this.$message.success("分销商品分类创建成功");
                    })
            } else {
                return false;
            }
        });
    },
    update(formName) {
        const set = this.$refs;
        set[formName].validate(valid => {
            if (valid) {
                if(!this.form.orderNum) {
                    this.form.orderNum = 0;
                }
                if(!this.form.adId) {
                    this.form.adId = 0;
                }
                if(!this.form.listAdId) {
                    this.form.listAdId = 0;
                }
                this.dialogFormVisible = false;
                this.form.password = undefined;
                retail_product_cat_edit(this.form.id, this.form).then(() => {
                    this.dialogFormVisible = false;
                    // this.getList();
                    this.getTree();
                    this.$message.success("分销商品分类更新成功");
                });
            } else {
                return false;
            }
        });
    },
    cancel(formName) {
        this.dialogFormVisible = false;
        this.$refs[formName].resetFields();
    },
    handleUpdate(row) {
        retail_product_cat_detail(row.id)
            .then(response => {
                this.form = response.data;
                if(this.form.adId) {
                    // this.form.adId = "" + this.form.adId;
                } else {
                    this.form.adId = undefined;
                }
                if(this.form.listAdId) {
                    // this.form.listAdId = "" + this.form.listAdId;
                } else {
                    this.form.listAdId = undefined;
                }
                let a = response.data.parentIds.split(",");
                let pids = [];
                a.forEach((item)=>{
                    if(item > 0) {
                        pids.push("" + item + "")
                    }
                })
                this.form.parentIdList = pids;
                // console.log(pids)
                this.dialogFormVisible = true;
                this.dialogStatus = 'update';
            });
    },
    handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                retail_product_cat_del(row.id)
                    .then(() => {
                        this.$message.success("分销商品分类删除成功");
                        this.getTree();
                    });
            }).catch(()=>{});
    },
    dialogClose() {
        this.$refs.form.resetFields();
    },
    handleFilter() {
        this.getTree();
    }
  }
};
</script>
